package logic

import (
	"context"
	"errors"
	"wxapi/internal/services"

	"wxapi/internal/svc"
	"wxapi/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UserLoginLogic) UserLogin(req *types.UserLoginReq) (resp *types.UserLoginResp, err error) {
	user := services.CreateUser(l.ctx, l.svcCtx, req.OpenId, req.UnionId, req.Nickname, req.Avatar, req.Country, req.Province, req.City, req.Gender)
	if user == nil || user.ID == 0 {
		return nil, errors.New("登录失败")
	}

	err = services.RemoveSession(l.ctx, l.svcCtx, user)
	if err != nil {
		return nil, err
	}

	session, err := services.CreateSession(l.ctx, l.svcCtx, user)
	if err != nil {
		return nil, err
	}

	nickname := user.Nickname
	if user.UserInfo.UserName != "" {
		nickname = user.UserInfo.UserName
	}

	resp = &types.UserLoginResp{
		Session:  session,
		Username: nickname,
		Avatar:   user.Avatar,
	}

	return
}
